/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

API.form = API.form || {};

API.form.Selector = function (config){
    
     API.apply(this, config, {
        store: '',
        description: '',
        value: '',
        name: '',
        class: 'form-input',
        defaultValue: -1,
        defaultDescription: '',
        text: '',
        autoLoad: true,
        listeners: {
            change: function(){}
        }        
    });
    
    var t = document.createTextNode(this.text),
        s = document.createElement('select'),
        p = document.createElement('p');

    s.name = this.name;
    s.className = this.class;
    s.addEventListener('change', this.listeners.change, false);    

    p.appendChild(t);
    p.appendChild(s);
    
    this.DOM = p;
    
    this.getSelector = function(){
        return s;
    };
   
    if(this.autoLoad)
        this.load();
   
};

API.apply(API.form.Selector.prototype,{    
    
    hide : function(){
        this.DOM.style.display = 'none';
    },

    show : function(){
        this.DOM.style.display = 'block';
    },

    getName : function(){
        return this.getSelector().name;
    },

    clear : function(){
        var s = this.getSelector();
        while(s.length)s.remove(0);        
    },

    addOption : function(opt){
        this.getSelector().appendChild(opt);
    },

    addEventListener : function(a,b,c){
        this.getSelector().addEventListener(a,b,c);
    },
    
    getValue : function(){
        return this.getSelector().value;
    },
    
    load : function(){
        
        this.clear();
        
        this.addOption(new API.form.Option({
            value: this.defaultValue,
            description: this.defaultDescription
        }));

        var sel = this;
        if(this.store !== '' && this.store.getLength() >0){
            this.store.forEachValue(function(value){

               var v = value[sel.value] || -1;
               var d = value[sel.description] || '';
               
               sel.addOption( new API.form.Option({
                   value: v,
                   description: d
               }));  

            });        
        }
    }
    
});